package com.mad.game.view.graphics;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;

import com.mad.game.backend.GameDemo;
import com.mad.game.view.models.GameModel;
import com.mad.game.view.models.ModelPool;

public class Renderer {
	
	public static boolean RENDER_WIREFRAME = false ; 
	
	public static final void startRenderingPipeline(Graphics graphics, int w, int h){
		render((Graphics2D)graphics.create(), w, h); 
	}
	
	public static final void render(Graphics2D graphics, int w, int h){
		BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); 
		Graphics2D tmpGraphics = img.createGraphics(); 
		
		renderBackground(tmpGraphics, w, h);
		renderGameObjects(tmpGraphics); 
		
		AffineTransform tx = AffineTransform.getScaleInstance(1, -1);
		tx.translate(0, -h); 
		AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
		BufferedImage finalImage = op.filter(img, null);
		
		graphics.drawImage(finalImage, null, 0, 0);
		
		tmpGraphics.dispose(); 
		graphics.dispose(); 
	}
	
	private static final void renderBackground(Graphics2D graphics, int w, int h){
		graphics.setColor(Color.black); 
		graphics.fillRect(0, 0, w, h); 
	}

	private static final void renderGameObjects(Graphics2D graphics){
		for(GameModel g: GameDemo.getGameInstance().getModelPool().getModels().values())
			renderSingleGameObject(g, graphics); 
	}

	private static void renderSingleGameObject(GameModel g, Graphics2D graphics) {
		int deltaX = GameDemo.getGameInstance().getCameraPosition().getX(); 
		int deltaY = GameDemo.getGameInstance().getCameraPosition().getY(); 
		
		int x = (int)g.getPosition().getX()+deltaX ; 
		int y = (int)g.getPosition().getY()+deltaY; 
		int w = (int)g.getSize().getWidth() ; 
		int h = (int)g.getSize().getHeight() ; 

		Color modelColor = Color.white ; 
		
		if(ModelPool.isBullet(g)) modelColor = Color.gray ; 
		else if(ModelPool.isPlayer(g)) modelColor = Color.green ; 
		else if(ModelPool.isEnemy(g)) modelColor = Color.red ; 
		
		graphics.setColor(modelColor);
		
		if(RENDER_WIREFRAME) graphics.drawRect(x, y, w, h);
		else graphics.fillRect(x, y, w, h); 
	}
	
}
